const { secret } = require('../../config/global');
// const md5 = require('md5');
// 导入jwt
const jwt = require('jsonwebtoken');
const { verifyToken } = require('../../utils/util')
const { register, phoneIsExists, doLogin } = require('../../model/member')

// 登录处理函数
const login = async (req, res) => {
    const output = {
        code: 200,
        msg: '登录成功'
    }
    // 获取请求参数
    let { phone, verifyCode, account_type } = req.body;
    // 账号类型, 默认为1, 表示普通用户,2-企业用户;3-企业管理人员
    account_type = account_type ? account_type : 1;
    if (!phone || !verifyCode) {
        output.code = 500;
        output.msg = '参数错误: 未提交phone, verifyCode';
        return res.send(output);
    }
    if (req.session.verifyCode != verifyCode) {
        output.code = 500;
        output.msg = '验证码错误';
        return res.send(output);
    }
    const exists = await phoneIsExists(phone)
    if (!exists) {
        // 执行注册
        await register(phone)
    }
    // 执行登录
    const result = await doLogin(phone)
    if (result.errorCode == 500) {
        output.code = result.errorCode
        output.msg = result.msg
        // 账号被冻结
        return res.send(output);
    }
    output.data = {
        ...result
    }
    // 删除密码
    delete output.data.password;
    res.send(output);
}

// 发送短信验证码
const verifyCode = async (req, res) => {
    const output = {
        code: 200,
        msg: '操作成功'
    }
    const { phone } = req.query;
    if (!phone) {
        output.code = 500;
        output.msg = '参数错误';
        return res.send(output);
    }
    const randCode = Date.now().toString().slice(9, 13);
    // 将验证码保存到session中
    req.session.verifyCode = randCode
    // 设置cookie
    // res.cookie('verifyCode', randCode, { maxAge: 600000, httpOnly: false });
    // 读取cookie
    // req.cookies
    // 返回验证码
    output.data = randCode;
    res.send(output);
}


// 检查token是否过期
const checkToken = async (req, res) => {
    const { authorization } = req.headers;
    // 验证token是否合法
    const output = verifyToken(authorization)
    res.send(output);
}

// token续费
const refreshToken = async (req, res) => {
    const output = { code: 200, msg: '操作成功' }
    // 获取refresh_token
    const refresh_token = req.body.refresh_token;
    try {
        // 解析refresh_token
        var decoded = jwt.verify(refresh_token, secret);
        if (!decoded) {
            output.code = 405;
            output.msg = 'refresh_token不合法或已过期';
            return res.send(output);
        }
        // refresh_token中保存的数据{id,account_type,phone}
        const { id, account_type, phone } = decoded
        // 重新生成token
        const newToken = jwt.sign({ id, account_type, phone }, secret, { expiresIn: '1h' });
        // 重新生成refresh_token
        const newRefreshToken = jwt.sign({ id, account_type, phone }, secret, { expiresIn: '2h' });
        output.data = {
            token: newToken, refresh_token: newRefreshToken
        }
        return res.send(output)
    } catch (err) {
        // err
        if (!decoded) {
            output.code = 405;
            output.msg = 'refresh_token不合法或已过期';
            return res.send(output);
        }
    }
    res.send(output)
}


module.exports = {
    login, verifyCode, checkToken, refreshToken
};